<?php

namespace app\admin\controller\business;

//引入进来基类控制器
use app\common\controller\Backend;

/**
 * 客户公海控制器
 * 涉及表：business、admin、business_receive
 */
class HighSea extends Backend
{
  //设置关联查询
  // 如果不设置这个，则会出现id冲突
  protected $relationSearch = true;

  //当前模型
  protected $model = null;

  //当前无须登录方法
  protected $noNeedLogin = [];

  //无需鉴权的方法,但需要登录
  protected $noNeedRight = [];

  //构造函数
  public function __construct()
  {
    parent::__construct();

    //将控制器和模型关联
    $this->model = model('Business.Business');
    $this->SourceModel = model('Business.Source');
    $this->ReceiveModel = model('Business.Receive');
    $this->AdminModel = model('Business.Admin');
  }

  // 列表
  public function index()
  {

    //将请求当中所有的参数去除html标签，去掉两边空白
    $this->request->filter(['strip_tags', 'trim']);

    // 判断是否有ajax
    if ($this->request->isAjax()) {
      //获取表格所提交过来筛选和排序的一些参数
      // 偏移量：$offset， 每页显示多少：$limit
      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      // 表格需要两个返回值参数 总条数，分页的数据
      // 总条数
      $total = $this->model
        ->with(['Source'])
        ->where('adminid', NULL)
        ->where($where)
        ->order($sort, $order)
        ->count();

      // 每一页展示的数据
      $list = $this->model
        ->with(['Source'])
        ->where('adminid', NULL)
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();

      // 组装数据
      $result = [
        'total' => $total,
        'rows' => $list,
      ];

      // 返回json格式数据给ajax
      return json($result);
    }

    // 模板渲染
    return $this->view->fetch();
  }

  // 领取
  /**
   * 涉及表：business(更新)、reveive(插入)
   */
  public function apply($ids = NULL)
  {
    // 查询当前客户是否存在
    $ids = !empty($ids) ?  explode(',', $ids) : [];
    $business = $this->model->all($ids);

    // 如果不存在
    if (!$business) {
      $this->error(__('No Results were found'));
      exit;
    }

    // 定义两个变量，用来接收用户表的数据和reveive表的数据
    $reveivelist = [];
    $businesslist = [];
    // 遍历渲染所有可能选中的id
    foreach ($business as $value) {
      $reveivelist[] = [
        'applyid' => $this->auth->id,
        'status' => 'apply',
        'busid' => $value['id']
      ];

      $businesslist[] = [
        'id' => $value['id'],
        'adminid' => $this->auth->id,
      ];
    };

    // 更新用户表，插入reveive表
    // 开启事务
    $this->model->startTrans();
    $this->ReceiveModel->startTrans();

    // 更新用户表
    $BusinessStatus = $this->model->saveAll($businesslist);
    // 判断是否更新成功
    if ($BusinessStatus === FALSE) {
      // 提示
      $this->error($this->model->getError());
    }

    // 插入reveive表
    $ReceiveStatus = $this->ReceiveModel->saveAll($reveivelist);
    // 判断是否插入成功
    if ($ReceiveStatus === FALSE) {
      // 回滚到更新
      $this->model->rollback();
      // 提示
      $this->error($this->ReceiveModel->getError());
    }

    if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
      $this->model->rollback();
      $this->ReceiveModel->rollback();
      $this->error('申请失败');
    } else {
      // 如果两个都成功，则可以提交了
      $this->model->commit();
      $this->ReceiveModel->commit();
      $this->success('申请成功');
    }
  }

  // 分配
  /**
   * 涉及表：business、reveive
   */
  public function recovery($ids = NULL)
  {
    // 查询当前客户是否存在
    $ids = !empty($ids) ?  explode(',', $ids) : [];
    $business = $this->model->all($ids);
    // 如果不存在
    if (!$business) {
      $this->error(__('No Results were found'));
      exit;
    }

    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收row前缀请求参数，并返回一个数组类型
      $params = $this->request->param('business/a');
      // 定义两个变量，用来接收用户表的数据和reveive表的数据
      $reveivelist = [];
      $businesslist = [];
      // 遍历渲染所有可能选中的id
      foreach ($business as $value) {
        $reveivelist[] = [
          'applyid' => $params['adminid'],
          'status' => 'allot',
          'busid' => $value['id']
        ];

        $businesslist[] = [
          'id' => $value['id'],
          'adminid' => $params['adminid'],
        ];
      };

      // 更新用户表，插入reveive表
      // 开启事务
      $this->model->startTrans();
      $this->ReceiveModel->startTrans();

      // 更新用户表
      $BusinessStatus = $this->model->saveAll($businesslist);
      // 判断是否更新成功
      if ($BusinessStatus === FALSE) {
        // 提示
        $this->error($this->model->getError());
      }

      // 插入reveive表
      $ReceiveStatus = $this->ReceiveModel->saveAll($reveivelist);
      // 判断是否插入成功
      if ($ReceiveStatus === FALSE) {
        // 回滚到更新
        $this->model->rollback();
        // 提示
        $this->error($this->ReceiveModel->getError());
      }

      if ($ReceiveStatus === FALSE || $BusinessStatus === FALSE) {
        $this->model->rollback();
        $this->ReceiveModel->rollback();
        $this->error('分配失败！！');
      } else {
        // 如果两个都成功，则可以提交了
        $this->model->commit();
        $this->ReceiveModel->commit();
        $this->success('分配成功！！');
      }
    }

    // 查询所有管理人员
    $admin = $this->AdminModel->column('id, username');
    // 赋值数据返回到模板中
    $this->assign([
      'business' => $business,
      'admin' => $admin
    ]);

    // 模板渲染
    return $this->view->fetch();
  }

  // 删除
  public function del($ids = NULL)
  {
    // 查询用户是否存在，并将其转换为数组分开
    $ids = !empty($ids) ?  explode(',', $ids) : [];

    // 查询出用户的指定字段id
    $business = $this->model->column('id');

    // 遍历出所有的id值，判断id是否存在$business里面
    foreach ($ids as $item) {
      if (!in_array($item, $business)) {
        $this->error(__('没有找到该用户'));
        exit;
      }
    }

    // 删除
    $result = $this->model->destroy($ids);

    if ($result === false) {
      $this->error($this->model->getError());
      exit;
    }

    $this->success();
    exit;
  }
}
